//
//  HistoryScreen.m
//  Gekko
//
//  Created by jose on 02/06/13.
//  Copyright (c) 2013 Jose Luis Lopez. All rights reserved.
//

#import "HistoryScreen.h"

@interface HistoryScreen ()

@end

@implementation HistoryScreen

@synthesize arrayReceipts, tableView, dateFormatter;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [[ReceiptController shared] setDelegate:self];

    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];

    arrayReceipts = [ReceiptsHolder sharedReceiptsHolder].arrayReceipts;//[ArchiverUnarchiver unarchiveReceipts];
    [tableView reloadData];

    [tableView setClipsToBounds:NO];
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
    [swipeGesture setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [self.tableView addGestureRecognizer:swipeGesture];
    
    UISwipeGestureRecognizer *swipeGestureR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
    [swipeGestureR setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.tableView addGestureRecognizer:swipeGestureR];
    
}

-(void)viewWillAppear:(BOOL)animated {
    
    [self.navigationController.view setNeedsLayout];
    [self.tabBarController.view setNeedsLayout];
    
    NSLog(@"Reload viewWillAppear");
    
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:kKeyShouldClear] integerValue] == 1)  {
        arrayReceipts = [NSMutableArray array];
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:kKeyShouldClear];
    } else
        arrayReceipts = [ReceiptsHolder sharedReceiptsHolder].arrayReceipts;
    
    
    [self.tableView reloadData];
    [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:kKeyShoudReload];

}

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0)
        return 57;
    else if (indexPath.row <= [arrayReceipts count])
        return 80;
    else
        return 11;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [arrayReceipts count] + 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableV cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    if (indexPath.row == 0) {
        
        cell = [tableV dequeueReusableCellWithIdentifier:@"HeaderCell"];
        UILabel *title = (UILabel *)[cell viewWithTag:1];
        [title setText:NSLocalizedString(@"HISTORY", nil)];
        [title setFont:[UIFont fontWithName:kFontBold size:26]];
        
        [((UIButton *)[cell viewWithTag:2]) addTarget:self action:@selector(uploadAll:) forControlEvents:UIControlEventTouchUpInside];
        [((UIButton *)[cell viewWithTag:2]) setTitle:NSLocalizedString(@"UPLOAD ALL", nil) forState:UIControlStateNormal];
        [((UIButton *)[cell viewWithTag:2]).titleLabel setFont:[UIFont fontWithName:kFontBold size:12]];
        
    } else if (indexPath.row == [arrayReceipts count] + 1)
        cell = [tableV dequeueReusableCellWithIdentifier:@"BottomCell"];
    else {
        cell = [tableV dequeueReusableCellWithIdentifier:@"RegularCell"];
    
        Receipt *receipt = [arrayReceipts objectAtIndex:(indexPath.row - 1)];
        
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//            [((UIImageView *)[cell viewWithTag:1]) setContentMode:UIViewContentModeScaleAspectFit];
//            if (receipt.image)
//                [((UIImageView *)[cell viewWithTag:1]) setImage:receipt.image];
//            [cell setNeedsDisplay];
//        });
        
        if (receipt.date) {
            UILabel *dateLabel = (UILabel *)[cell viewWithTag:2];
            [dateLabel setText:[dateFormatter stringFromDate:receipt.date]];
            [dateLabel setFont:[UIFont fontWithName:kFontBold size:16]];
        }
        if (receipt.totalAmount) {
            UILabel *amountLabel = (UILabel *)[cell viewWithTag:3];
            [amountLabel setText:[NSString stringWithFormat:@"€ %@", receipt.totalAmount]];
            [amountLabel setFont:[UIFont fontWithName:kFontBold size:16]];
        }
        if (receipt.description) {
            UILabel *descriptionLabel = (UILabel *)[cell viewWithTag:4];
            [descriptionLabel setText:receipt.description];
            [descriptionLabel setFont:[UIFont fontWithName:kFontLight size:14]];
        }
        if ([receipt.status isEqualToString:kStatusUploaded]) { //State uploaded
            
            [[cell viewWithTag:5] setBackgroundColor:[UIColor colorWithRed:128.0/255 green:186.0/255 blue:66.0/255 alpha:1]];
            [[cell viewWithTag:6] setHidden:YES];
            [[cell viewWithTag:8] setHidden:YES];
        } else if ([receipt.status isEqualToString:kStatusDraft]) { // State draft
            
            [[cell viewWithTag:5] setBackgroundColor:[UIColor colorWithRed:210.0/255 green:48.0/255 blue:66.0/255 alpha:1]];
            [[cell viewWithTag:6] setHidden:YES];
            [[cell viewWithTag:8] setHidden:YES];
        } else if([receipt.status isEqualToString:kStatusReady]) { // Ready for upload
            
            [[cell viewWithTag:5] setBackgroundColor:[UIColor colorWithRed:227.0/255 green:121.0/255 blue:38.0/255 alpha:1]];
            [[cell viewWithTag:6] setHidden:NO];
            [[cell viewWithTag:8] setHidden:YES];
            [((UIButton *)[cell viewWithTag:6]) addTarget:self action:@selector(uploadReceipt:) forControlEvents:UIControlEventTouchUpInside];
            [((UIButton *)[cell viewWithTag:6]) setTitle:NSLocalizedString(@"UPLOAD", nil) forState:UIControlStateNormal];
            [((UIButton *)[cell viewWithTag:6]).titleLabel setFont:[UIFont fontWithName:kFontBold size:12]];
        } else { // Uploading
            
            [[cell viewWithTag:5] setBackgroundColor:[UIColor colorWithRed:227.0/255 green:121.0/255 blue:38.0/255 alpha:1]];
            [[cell viewWithTag:6] setHidden:YES];
            [[cell viewWithTag:8] setHidden:NO];
            [((UIActivityIndicatorView *) [cell viewWithTag:8]) startAnimating];
        }
        [cell viewWithTag:5].frame = CGRectMake(297, 0, 12, 79);
        
        UIButton *deleteButton = (UIButton *)[cell viewWithTag:7];
        [deleteButton setHidden:YES];
        [deleteButton setTitle:NSLocalizedString(@"DELETE", nil) forState:UIControlStateNormal];
        [deleteButton.titleLabel setFont:[UIFont fontWithName:kFontBold size:14]];
        [deleteButton.titleLabel setTextColor:[UIColor whiteColor]];
        [deleteButton addTarget:self action:@selector(deleteReceipt:) forControlEvents:UIControlEventTouchUpInside];
    
    }
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"Selecting");
    if ((indexPath.row != 0) && (indexPath.row != [arrayReceipts count] + 1)) {
        [Receipt setSharedReceipt:[arrayReceipts objectAtIndex:(indexPath.row - 1)]];
        [self performSegueWithIdentifier:@"PushToPreview" sender:self];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:@"PushToPreview"]) {
        
        ((DetailsScreen *)segue.destinationViewController).comesFromHistory = YES;
    }
}

-(void)swipeLeft:(UISwipeGestureRecognizer *)gesture {
    
    CGPoint swipeLocation = [gesture locationInView:tableView];
    NSIndexPath *swipedIndexPath = [tableView indexPathForRowAtPoint:swipeLocation];
    
    if ([((Receipt *)[arrayReceipts objectAtIndex:(swipedIndexPath.row - 1)]).status isEqualToString:kStatusDraft]) {
        
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
        
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^(void) {
            
            UIView *view = [cell viewWithTag:5];
            view.frame = CGRectMake(217, 0, 92, 79);
            
        }completion:^(BOOL res) {
            
            [[cell viewWithTag:7] setHidden:NO];
            [cell bringSubviewToFront:[cell viewWithTag:7]];
        }];
    }
}

-(void)swipeRight:(UISwipeGestureRecognizer*)gesture {
    
    CGPoint swipeLocation = [gesture locationInView:tableView];
    NSIndexPath *swipedIndexPath = [tableView indexPathForRowAtPoint:swipeLocation];
    
    if ([((Receipt *)[arrayReceipts objectAtIndex:(swipedIndexPath.row - 1)]).status isEqualToString:kStatusDraft]) {
        
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
        
        [[cell viewWithTag:7] setHidden:YES];
        
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^(void) {
            
            UIView *view = [cell viewWithTag:5];
            view.frame = CGRectMake(297, 0, 12, 79);

        }completion:^(BOOL res) {
            
        }];
    }
}

-(void)deleteReceipt:(UIButton *)sender {
    
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil) {

        [ArchiverUnarchiver deleteReceipt:[arrayReceipts objectAtIndex:(indexPath.row - 1)]];
        [arrayReceipts removeObjectAtIndex:(indexPath.row - 1)];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

-(void)uploadReceipt:(UIButton *)sender {

    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil) {
     
        Receipt *receipt = [arrayReceipts objectAtIndex:(indexPath.row - 1)];
        receipt.status = kStatusUploading;
        [tableView reloadData];
        [[ReceiptController shared] uploadReceipt:receipt];
    }
}

-(void)uploadAll:(UIButton *)sender {
    
    NSLog(@"Uploading all");
    BOOL shouldReload = NO;
    for (Receipt *receipt in arrayReceipts) {
        if ([receipt.status isEqualToString:kStatusReady]) {
            
            receipt.status = kStatusUploading;

            [[ReceiptController shared] uploadReceipt:receipt];
            
            shouldReload = YES;
        }
    }
    
    [tableView reloadData]; 
}

#pragma mark - Delegate callbacks

-(void)uploadFailedWithId:(NSString *)idi {

    NSLog(@"Upload failed");
    for (Receipt * receipt in arrayReceipts) {
        
        if ([receipt.idi isEqualToString:idi]) {
            receipt.status = kStatusReady;
            break;
        }
    }
    
    [tableView reloadData];
}

-(void)uploadSuccededWithId:(NSString *)idi {
 
    NSLog(@"Upload succeded");
    for (Receipt * receipt in arrayReceipts) {
        
        if ([receipt.idi isEqualToString:idi]) {
            receipt.status = kStatusUploaded;
            break;
        }
    }
    
    [tableView reloadData];
}

@end
